package com.ftg.learn.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ftg.learn.comm.RMessCommEnum;
import com.ftg.learn.util.JwtUtils;
import com.ftg.learn.util.R;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;

/**
 * @author 布衣
 */
@Component
public class MyInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        String token = request.getHeader("token");
        if (token == null || token.isEmpty()) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            writeResponse(response, R.build(RMessCommEnum.NOT_FOUND_TOKEN));
            return false;
        }

        if (JwtUtils.validateToken(token)) {
            return true;
        } else {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            writeResponse(response, R.build(RMessCommEnum.TOKEN_NONE_VALID));
            return false;
        }
    }
    
    /**
     * 将R对象以JSON格式写入响应
     * @param response HTTP响应
     * @param result 返回结果
     * @throws IOException IO异常
     */
    private void writeResponse(HttpServletResponse response, R<?> result) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        ObjectMapper objectMapper = new ObjectMapper();
        response.getWriter().write(objectMapper.writeValueAsString(result));
    }

}
